package Q4;
/*
  使用基于 tcp 协议的编程模型实现将 UserMessage 类型对象由客户端发送给服务器；
 */

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientSide {

    public static void main(String[] args) {

        //1.创建Socket类型的对象并提供服务器的主机名和端口
        Socket client = null;
        Scanner sc = null;
        ObjectOutputStream send = null;
        ObjectInputStream recieve = null;
        try {
            client = new Socket("127.0.0.1",6666);
            System.out.println("服务器连接成功！");
            sc = new Scanner(System.in);
            //2.使用输入输出流进行通信
            send = new ObjectOutputStream(client.getOutputStream());
            recieve = new ObjectInputStream(client.getInputStream());
            while (true){
                System.out.println("请输入用户名：");
                String name = sc.next();
                System.out.println("请输入用户密码");
                String password = sc.next();
                User user = new User(name, password);
                UserMassage message = new UserMassage("check", user);
                System.out.println("输入的用户名为："+ message.getClient() + "\n目前状态是："+message.getType());
                send.writeObject(message);
                System.out.println("已经向服务器发送了信息");
                UserMassage back_message = (UserMassage) recieve.readObject();
                System.out.println("已接收到服务器的返回消息" + back_message.getType());
                if(back_message.getType().equals("success")){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //3.关闭Socket并释放有关的资源
            if(null != send){
                try {
                    send.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != recieve){
                try {
                    recieve.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != client){
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        }
    }
}
